import { baseRequestClient, requestClient } from '#/api/request';

export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    tenant_id?: string;
    login_name?: string;
    password?: string;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
      access_token: string;      
      refresh_token?: string;
      expires_in?: number;    
  }

  export interface RefreshTokenResult {
    data: string;
    status: number;
  }
}

/**
 * 登录
 */
export async function loginApi(data: AuthApi.LoginParams): Promise<AuthApi.LoginResult> {
  const response = await requestClient.post('/api/v1/auth/login', data);
  const loginResult: AuthApi.LoginResult = response.data;
  return loginResult;
}

// export async function getUserInfoApi(): Promise<UserInfo> {
//   const response = await requestClient.get('/api/v1/auth/me');
  
//   // 映射后端字段到前端期望的字段
//   const backendUser = response.data;
//   const userInfo: UserInfo = {
//     userId: backendUser.id,
//     username: backendUser.login_name,
//     realName: backendUser.full_name || backendUser.login_name,
//     avatar: backendUser.avatar || '',
//     roles: backendUser.roles?.map((role: any) => role.name) || [],
//     homePath: '/dashboard', // 设置默认主页路径
//     ...backendUser, // 保留其他字段
//   };
  
//   return userInfo;
// }

/**
 * 刷新accessToken
 */
export async function refreshTokenApi() {
  return baseRequestClient.post<AuthApi.RefreshTokenResult>('/api/v1/auth/refresh', {
    withCredentials: true,
  });
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return baseRequestClient.post('/api/v1/auth/logout', {
    withCredentials: true,
  });
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/api/v1/auth/codes');
}
